package com.hctg.forced2sleep.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.actor.myandroidframework.utils.LogUtils;
import com.actor.myandroidframework.utils.TextUtils2;
import com.blankj.utilcode.util.NotificationUtils;
import com.blankj.utilcode.util.Utils;
import com.hctg.forced2sleep.R;
import com.hctg.forced2sleep.easy_window.PageElementSelectEasyWindow;
import com.hctg.forced2sleep.utils.AccessibilityUtils;
import com.hjq.window.EasyWindow;

/**
 * description: 辅助功能
 * company    :
 * @author    : ldf
 * date       : 2024/4/19 on 20:31
 */
public class MyAccessibilityService extends AccessibilityService {

    protected int id = 2;
    protected int requestCode = 6;

    protected static MyAccessibilityService instance;

    @Nullable
    public static MyAccessibilityService get() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.error("onCreate();");
        fitForegroundService();
    }

    private void fitForegroundService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtils.notify(id, new Utils.Consumer<NotificationCompat.Builder>() {
                @Override
                public void accept(NotificationCompat.Builder builder) {
                    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.item_notification);
                    Intent intent1 = new Intent(MyAccessibilityService.this, MyAccessibilityService.class);
                    intent1.putExtra("command","CommandPlay");
                    PendingIntent pIntent1 =  PendingIntent.getService(MyAccessibilityService.this,
                            requestCode, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
                    remoteViews.setOnClickPendingIntent(R.id.ll, pIntent1);
                    builder
                            .setSmallIcon(R.drawable.logo)
                            .setCustomContentView(remoteViews)
                            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE);

                    //开启前台进程: 高版本要调用这句, 否则过几秒后会退出
                    startForeground(id, builder.build());
                }
            });
        }
    }

    /**
     * 连接服务后,一般是在授权成功后会接收到
     * 系统会在成功连接上你的服务的时候调用这个方法，在这个方法里你可以做一下初始化工作，
     * 例如设备的声音震动管理，也可以调用setServiceInfo()进行配置工作。
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        LogUtils.error("onServiceConnected();");

        /**
         * 通过在Service连接到无障碍服务的回调，调用setServiceInfo方法，可以在在运行时调整无障碍服务的配置：
         * 但是，使用此方法时，并非所有配置选项都可用
         */
        if (false) {
            AccessibilityServiceInfo accessibilityServiceInfo = new AccessibilityServiceInfo();
            accessibilityServiceInfo.eventTypes = (AccessibilityEvent.TYPE_WINDOWS_CHANGED
                    | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
                    | AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
                    | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
                    | AccessibilityEvent.TYPE_VIEW_CLICKED
            );
            accessibilityServiceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
            accessibilityServiceInfo.notificationTimeout = 0;
            accessibilityServiceInfo.flags = AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
                    | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
                    | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
                    | AccessibilityServiceInfo.DEFAULT;
            // 如果这里指定了包名则只会收到对应包名应用的事件
            accessibilityServiceInfo.packageNames = new String[] {"com.yanggui.animatortest"};
            setServiceInfo(accessibilityServiceInfo);
        }
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        CharSequence packageName = event.getPackageName();//当前页面包名
        CharSequence className = event.getClassName();//当前页面类名 or 当前View的类名
        int eventType = event.getEventType();
        String info = TextUtils2.getStringFormat("eventType: %d, 包名: %s, 类名: %s", eventType, packageName, className);
        LogUtils.error(info);
        LogUtils.errorFormat("packageName: %s", getPackageName());
        if (TextUtils.equals(getPackageName(), packageName)) {
            //当前是元素选择 EasyWindow
            if (EasyWindow.existShowingByClass(PageElementSelectEasyWindow.class)) {
                LogUtils.error("PageElementSelectEasyWindow, return");
                return;
            }
        }

        //根布局是轮轮哥的FrameLayout...
//        if (className != CantGetAccessibilityAble.class.getName()) {
//        }
        AccessibilityUtils.updateEvent(this, event);

        switch (eventType) {
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                break;
            case AccessibilityEvent.TYPE_VIEW_LONG_CLICKED:
    //            LogUtils.error(packageName);
                break;
            default:
                break;
            }
    }

    /**
     * 锁屏, 不管有没有设置密码, 都能锁屏(锁屏后会息屏)
     */
    public void actionLockScreen() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN);
    }

    /**
     * 返回键
     */
    public void actionBack() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }

    /**
     * 跳转桌面
     */
    public void actionHome() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
    }

    /**
     * 打开通知
     */
    public void actionNotification() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS);
    }

    /**
     * 打开最近应用
     */
    public void actionRecent() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
    }

    /**
     * 打开长按电源键的弹框
     */
    public void actionPowerDialog() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);
    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        LogUtils.errorFormat("getKeyCode: %d", event.getKeyCode());
        return super.onKeyEvent(event);
    }

    /**
     * 当系统想要中断您的服务正在提供的反馈（通常是为了响应将焦点移到其他控件等用户操作）时调用此方法。
     * 此方法可以在服务的整个生命周期内调用多次。
     */
    @Override
    public void onInterrupt() {
        instance = null;
        //辅助功能服务中断，如授权关闭或者将服务杀死
        LogUtils.error("onInterrupt();");
    }

    /**
     * 系统会在系统即将关闭无障碍服务时调用此方法。
     * 使用此方法执行任何一次性关闭过程，包括取消分配用户反馈系统服务，例如音频管理器或设备振动器。
     * 手动停止无障碍服务后, 会回调
     */
    @Override
    public boolean onUnbind(Intent intent) {
        instance = null;
        LogUtils.error("onUnbind!");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
        LogUtils.error("onDestroy();");
        //
//        stopSelf();
//        disableSelf();
    }



    ///////////////////////////////////////////////////////////////////////////
    // 以下方法没有调用过!
    ///////////////////////////////////////////////////////////////////////////
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        LogUtils.errorFormat("onStart, startId=%d", startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.errorFormat("onStartCommand, flags=%d, startId=%d", flags, startId);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        LogUtils.error("onRebind!");
    }
}